<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-card class="app-card apple-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.customer_name" placeholder="请输入客户名称" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="queryParams.order_number" placeholder="请输入订单号" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="授权域名">
          <el-input v-model="queryParams.authorized_domain" placeholder="请输入授权域名" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="激活人">
          <el-input v-model="queryParams.nickname" placeholder="请输入激活人" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.order_status" placeholder="请选择" clearable class="apple-select">
            <el-option :value="0" label="未激活" />
            <el-option :value="1" label="已激活" />
            <el-option :value="2" label="临时IP激活" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期">
          <el-date-picker
            v-model="dateRange.order_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="激活日期">
          <el-date-picker
            v-model="dateRange.activation_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="购买产品">
          <el-select v-model="queryParams.product_name" 
            filterable
            remote
            reserve-keyword
            placeholder="请输入产品名称" 
            :remote-method="remoteProductSearch"
            :loading="productLoading"
            clearable 
            class="apple-select">
            <el-option v-for="item in productOptions" :key="item.id" :label="item.product_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已开票">
          <el-radio-group v-model="queryParams.is_invoice" class="apple-radio-group">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
            <el-radio :label="null">全部</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否双倍提成">
          <el-radio-group v-model="queryParams.is_double_coms" class="apple-radio-group">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
            <el-radio :label="null">全部</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="apple-button primary-button">点击查询</el-button>
          <el-button @click="resetQuery" class="apple-button">重置查询条件</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表区域 -->
    <el-card class="app-card apple-card">
      <div class="table-header">
        <div class="left-buttons">
          <el-button type="primary" @click="handleAdd" class="apple-button primary-button">
            <i class="el-icon-plus"></i> 添加订单记录
          </el-button>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete" class="apple-button danger-button">
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <el-button type="warning" :disabled="selectedIds.length === 0" @click="handleBatchMarkInvoice" class="apple-button warning-button">
            <i class="el-icon-document"></i> 批量标记开票
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="success" @click="handleExport" :loading="exportLoading" class="apple-button success-button">
            <i class="el-icon-download"></i> {{ isFiltered ? '导出筛选数据' : '导出全部数据' }}
          </el-button>
          <el-button @click="handleImportClick" class="apple-button">
            <i class="el-icon-upload2"></i> 导入
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        class="apple-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="操作" width="150" fixed="left">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)" class="apple-link-button">编辑</el-button>
            <el-button type="success" link @click="handleCopy(scope.row)" class="apple-link-button">复制</el-button>
            <el-button type="info" link @click="handleView(scope.row)" class="apple-link-button">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="下单日期" width="100" sortable />
        <el-table-column prop="customer_name_display" label="下单客户" width="150" />
        <el-table-column prop="order_source_display" label="订单来源" width="120" />
        <el-table-column prop="order_number" label="订单号" width="180" />
        <el-table-column prop="product_name_display" label="购买产品" width="150" />
        <el-table-column prop="order_amount" label="订单金额" width="100" sortable />
        <el-table-column prop="purchase_years_display" label="购买年限" width="100" />
        <el-table-column prop="order_status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.order_status === 1 ? 'success' : 'warning'" class="apple-tag">
              {{ scope.row.order_status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_double_coms" label="双倍提成" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.is_double_coms === 1 ? 'danger' : 'info'" class="apple-tag">
              {{ scope.row.is_double_coms === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activation_date" label="激活日期" width="100" sortable />
        <el-table-column prop="expiration_date" label="到期日期" width="100" sortable />
        <el-table-column prop="authorized_domain" label="授权域名" width="180" show-overflow-tooltip />
      </el-table>
      
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="apple-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑订单弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      custom-class="apple-dialog"
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单客户" prop="customer_name">
              <div class="customer-select-wrapper">
                <el-select
                  v-model="orderForm.customer_name"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入客户名称"
                  :remote-method="remoteCustomerSearch"
                  :loading="customerLoading"
                  style="width: 100%"
                  @change="handleCustomerSelectChange"
                  class="apple-select"
                >
                  <el-option
                    v-for="item in customerOptions"
                    :key="item.id"
                    :label="item.customer_name"
                    :value="item.id"
                  />
                  <el-option
                    v-if="searchCustomerKeyword && showCreateOption"
                    :value="'create_new'"
                    :label="`创建新客户: ${searchCustomerKeyword}`"
                  />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单号" prop="order_number">
              <el-input v-model="orderForm.order_number" placeholder="请输入订单号" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买产品" prop="product_name">
              <el-select v-model="orderForm.product_name" 
                filterable
                remote
                reserve-keyword
                placeholder="请输入产品名称"
                :remote-method="remoteProductSearch" 
                :loading="productLoading"
                style="width: 100%" 
                class="apple-select">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.product_name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买年限" prop="purchase_years">
              <el-select v-model="orderForm.purchase_years" placeholder="请选择年限" style="width: 100%" class="apple-select">
                <el-option :value="0" label="永久" />
                <el-option :value="1" label="1年" />
                <el-option :value="2" label="2年" />
                <el-option :value="3" label="3年" />
                <el-option :value="4" label="4年" />
                <el-option :value="5" label="5年" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="激活日期" prop="activation_date">
              <el-date-picker
                v-model="orderForm.activation_date"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                class="apple-date-picker"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="激活人" prop="nickname">
              <el-select 
                v-model="orderForm.nickname" 
                filterable
                remote
                reserve-keyword
                placeholder="请输入激活人昵称"
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                style="width: 100%" 
                class="apple-select">
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                >
                  <span :style="item.role === 1 ? 'color: #909399;' : ''">{{ item.nickname }}</span>
                </el-option>
                <div v-if="userOptions.length === 0" style="color: red; font-size: 12px;">没有可用的激活人选项</div>
              </el-select>
              <div class="form-tip" style="font-size: 12px; color: #909399; margin-top: 5px;">管理员可作为激活人，但不参与薪资计算</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否已开票" prop="is_invoice">
              <el-radio-group v-model="orderForm.is_invoice" class="apple-radio-group">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否双倍提成" prop="is_double_coms">
              <el-radio-group v-model="orderForm.is_double_coms" class="apple-radio-group">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单来源" prop="order_source">
              <el-select v-model="orderForm.order_source" placeholder="请选择订单来源" style="width: 100%" class="apple-select">
                <el-option :value="0" label="Newbe工作室" />
                <el-option :value="1" label="纽币德信息科技" />
                <el-option :value="2" label="官方网站" />
                <el-option :value="3" label="其它" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单日期" prop="order_date">
              <el-date-picker
                v-model="orderForm.order_date"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                class="apple-date-picker"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单金额" prop="order_amount">
              <el-input-number v-model="orderForm.order_amount" :precision="2" :step="0.1" :min="0" style="width: 100%" class="apple-input-number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="order_status">
              <el-select v-model="orderForm.order_status" placeholder="请选择订单状态" style="width: 100%" class="apple-select">
                <el-option :value="0" label="未激活" />
                <el-option :value="1" label="已激活" />
                <el-option :value="2" label="临时IP激活" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授权域名" prop="authorized_domain">
              <el-input v-model="orderForm.authorized_domain" placeholder="请输入客户域名或IP地址" class="apple-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授权码" prop="authorization_code">
              <el-input v-model="orderForm.authorization_code" placeholder="请输入token或激活码" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订单备注" prop="order_remarks">
          <el-input
            v-model="orderForm.order_remarks"
            type="textarea"
            placeholder="请输入备注信息"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="apple-button">取消</el-button>
        <el-button type="primary" @click="submitOrderForm" class="apple-button primary-button">提交</el-button>
      </template>
    </el-dialog>

    <!-- 新建客户弹窗 -->
    <el-dialog
      title="新建客户"
      v-model="customerDialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
      custom-class="apple-dialog"
    >
      <el-form
        ref="customerFormRef"
        :model="customerForm"
        :rules="customerRules"
        label-width="100px"
      >
        <el-form-item label="客户名称" prop="customer_name">
          <el-input v-model="customerForm.customer_name" placeholder="请输入客户名称" class="apple-input" />
        </el-form-item>
        <el-form-item label="客户来源" prop="customer_source">
          <el-select v-model="customerForm.customer_source" placeholder="请选择客户来源" style="width: 100%" class="apple-select">
            <el-option :value="0" label="Newbe工作室" />
            <el-option :value="1" label="纽币德信息科技" />
            <el-option :value="2" label="官方网站" />
            <el-option :value="3" label="其它" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone_number">
          <el-input v-model="customerForm.phone_number" placeholder="请输入手机号码" class="apple-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="customerDialogVisible = false" class="apple-button">取消</el-button>
        <el-button type="primary" @click="submitCustomerForm" class="apple-button primary-button">提交</el-button>
      </template>
    </el-dialog>

    <!-- 导入订单对话框 -->
    <el-dialog
      title="导入订单数据"
      v-model="importDialogVisible"
      width="900px"
      append-to-body
      destroy-on-close
      custom-class="apple-dialog import-dialog"
    >
      <div class="import-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="template-download">
              <h4>下载导入模板</h4>
              <p>请先下载导入模板，按照模板格式填写订单数据后再进行导入：</p>
              <el-button type="primary" @click="downloadTemplate" class="apple-button primary-button">下载导入模板</el-button>
            </div>
            
            <el-divider></el-divider>
            
            <div class="upload-section">
              <h4>文件上传</h4>
              <el-upload
                class="upload-box"
                drag
                action="#"
                :http-request="handleFileUpload"
                :show-file-list="true"
                :limit="1"
                :multiple="false"
                :auto-upload="true"
                accept=".xlsx,.xls"
                ref="uploadRef"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或 <em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传Excel文件（.xlsx或.xls格式）
                  </div>
                </template>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="import-format-container">
              <h4>导入格式说明</h4>
              <div class="import-format-tips">
                <p><strong>必填字段：</strong>订单号、客户名称、产品名称、订单金额、购买年限、订单状态、授权域名、下单日期、订单来源</p>
                <p><strong>字段格式要求：</strong></p>
                <ul>
                  <li><b>客户名称</b>：必须是系统中已存在的客户，否则导入失败</li>
                  <li><b>产品名称</b>：必须是系统中已存在的产品，否则导入失败</li>
                  <li><b>订单来源</b>：必须是以下值之一：Newbe工作室、纽币德信息科技、官方网站、其它</li>
                  <li><b>购买年限</b>：必须是以下值之一：永久、1年、2年、3年、4年、5年</li>
                  <li><b>订单状态</b>：必须是以下值之一：未激活、已激活、临时IP激活</li>
                  <li><b>下单日期</b>：日期格式为 YYYY-MM-DD，例如：2025-04-28</li>
                  <li><b>是否已开票</b>：必须是以下值之一：是、否</li>
                  <li><b>是否双倍提成</b>：必须是以下值之一：是、否</li>
                  <li><b>激活人</b>：如果填写，必须是系统中已存在的用户昵称</li>
                </ul>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="importDialogVisible = false" class="apple-button">取消</el-button>
        <el-button type="primary" @click="submitImport" :loading="importLoading" class="apple-button primary-button">开始导入</el-button>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="orderDetailVisible"
      width="850px"
      append-to-body
      destroy-on-close
      custom-class="apple-dialog"
    >
      <div v-if="orderDetail" class="order-detail-container">
        <el-descriptions border :column="2" size="large">
          <el-descriptions-item label="订单号">
            <span class="info-text">{{ orderDetail.order_number }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="下单日期">
            <span class="info-text">{{ orderDetail.order_date }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            <span class="info-text">{{ orderDetail.customer_name_display }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="产品名称">
            <span class="info-text">{{ orderDetail.product_name_display }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="price-text">¥ {{ orderDetail.order_amount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="购买年限">
            <span class="info-text">{{ orderDetail.purchase_years_display }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <span :class="['status-tag', orderDetail.order_status === 1 ? 'activated' : 'unactivated']">
              {{ orderDetail.order_status_display }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="是否已开票">
            <span :class="['status-tag', orderDetail.is_invoice === 1 ? 'yes' : 'no']">
              {{ orderDetail.is_invoice === 1 ? '是' : '否' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="授权域名">
            <span class="info-text">{{ orderDetail.authorized_domain }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="授权码">
            <span class="info-text">{{ orderDetail.authorization_code || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="激活日期">
            <span class="info-text">{{ orderDetail.activation_date || '未激活' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="激活人">
            <span class="info-text">{{ orderDetail.nickname_display || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="orderDetail.expiration_date" label="到期日期" :span="2">
            <span class="info-text">{{ orderDetail.expiration_date }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单备注" :span="2">
            <span class="info-text">{{ orderDetail.order_remarks || '无' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="orderDetailVisible = false" class="apple-button">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { 
  getOrderList, getOrder, createOrder, updateOrder, /* deleteOrder, */ 
  batchDeleteOrders, batchMarkInvoice, exportOrders, getImportTemplate, importOrders 
} from '@/api/orders';
import { getCustomerList, createCustomer } from '@/api/customers';
import { getProductList } from '@/api/products';
import { getUserList } from '@/api/users';

// 查询参数
const queryParams = reactive({
  customer_name: '',
  order_number: '',
  authorized_domain: '',
  nickname: '',
  order_status: null,
  product_name: null,
  is_invoice: null,
  is_double_coms: null,
  page: 1,
  page_size: 10
});

// 日期范围
const dateRange = reactive({
  order_date: [],
  activation_date: []
});

// 表格数据
const orderList = ref([]);
const loading = ref(false);
const selectedIds = ref([]);

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 下拉选项
const productOptions = ref([]);
const customerOptions = ref([]);
const userOptions = ref([
  // 添加默认模拟数据，确保激活人下拉菜单总是有选项
  { id: 1, nickname: '默认客服1' },
  { id: 2, nickname: '默认客服2' },
  { id: 3, nickname: '默认客服3' }
]);
const customerLoading = ref(false);
const productLoading = ref(false); // 添加产品加载状态
const userLoading = ref(false); // 添加用户加载状态
const searchCustomerKeyword = ref('');
const searchProductKeyword = ref(''); // 添加产品搜索关键词
const searchUserKeyword = ref(''); // 添加用户搜索关键词
const showCreateOption = ref(false);

// 表单相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加订单记录');
const orderForm = reactive({
  customer_name: null,
  order_number: '',
  product_name: null,
  purchase_years: 1,
  activation_date: '',
  nickname: null,
  is_invoice: 0,
  is_double_coms: 0,
  order_source: 0,
  order_date: new Date().toISOString().slice(0, 10),
  order_amount: 0,
  order_status: 0,
  authorized_domain: '',
  authorization_code: '',
  order_remarks: ''
});

// 表单规则
const rules = {
  customer_name: [{ required: true, message: '请选择客户', trigger: 'change' }],
  order_number: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  product_name: [{ required: true, message: '请选择产品', trigger: 'change' }],
  purchase_years: [{ required: true, message: '请选择购买年限', trigger: 'change' }],
  order_date: [{ required: true, message: '请选择下单日期', trigger: 'change' }],
  order_amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
  order_status: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
};

// 客户表单相关
const customerDialogVisible = ref(false);
const customerForm = reactive({
  customer_name: '',
  customer_source: 0,
  phone_number: ''
});

// 客户表单规则
const customerRules = {
  customer_name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  customer_source: [{ required: true, message: '请选择客户来源', trigger: 'change' }]
};

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const uploadRef = ref(null);
const importFile = ref(null);

// 修改表单引用名称
const orderFormRef = ref(null);
const customerFormRef = ref(null);

// 新增订单详情相关的响应式变量
const orderDetail = ref(null);
const orderDetailVisible = ref(false);

// 远程搜索客户
const remoteCustomerSearch = (query) => {
  if (query) {
    searchCustomerKeyword.value = query;
    customerLoading.value = true;
    getCustomerList({ customer_name: query })
      .then(response => {
        customerOptions.value = response.results;
        // 如果没有找到客户，显示创建新客户选项
        showCreateOption.value = response.results.length === 0;
      })
      .catch(error => {
        ElMessage.error('获取客户列表失败');
        console.error('获取客户列表失败:', error);
      })
      .finally(() => {
        customerLoading.value = false;
      });
  } else {
    customerOptions.value = [];
    showCreateOption.value = false;
  }
};

// 远程搜索产品
const remoteProductSearch = (query) => {
  if (query) {
    searchProductKeyword.value = query;
    productLoading.value = true;
    getProductList({ product_name: query, page_size: 20 })
      .then(response => {
        productOptions.value = response.results || [];
        console.log('搜索到产品:', productOptions.value.length);
      })
      .catch(error => {
        console.error('搜索产品失败:', error);
      })
      .finally(() => {
        productLoading.value = false;
      });
  } else {
    // 如果搜索词为空，加载更多产品
    loadProductOptions();
  }
};

// 远程搜索用户
const remoteUserSearch = (query) => {
  if (query) {
    searchUserKeyword.value = query;
    userLoading.value = true;
    getUserList({ nickname: query, page_size: 20 })
      .then(response => {
        let userData = [];
        
        // 处理不同的响应格式
        if (response && response.results && response.results.length > 0) {
          userData = response.results;
        } else if (response && response.data && response.data.items) {
          userData = response.data.items;
        } else if (response && response.data && response.data.length > 0) {
          userData = response.data;
        } else {
          console.warn('搜索用户返回了空结果');
          userOptions.value = [];
          userLoading.value = false;
          return;
        }
        
        // 格式化用户数据，添加角色信息
        if (userData && userData.length > 0) {
          const formattedData = userData.map(item => ({
            id: item.id,
            nickname: item.role === 1 ? `${item.nickname || `用户${item.id}`}` : (item.nickname || `用户${item.id}`),
            role: item.role || 0
          }));
          userOptions.value = formattedData;
        }
        
        console.log('搜索到用户:', userOptions.value.length);
      })
      .catch(error => {
        console.error('搜索用户失败:', error);
      })
      .finally(() => {
        userLoading.value = false;
      });
  } else {
    // 如果搜索词为空，加载默认用户
    loadUserOptions();
  }
};

// 声明导出加载状态
const exportLoading = ref(false);

// 计算属性：判断是否有筛选条件
const isFiltered = computed(() => {
  // 检查查询参数是否有值
  const hasQueryParams = Object.keys(queryParams).some(key => {
    if (key === 'page' || key === 'page_size') return false;
    return queryParams[key] !== null && queryParams[key] !== '' && 
           !(Array.isArray(queryParams[key]) && queryParams[key].length === 0);
  });
  
  // 检查日期范围是否有值
  const hasDateRange = (dateRange.order_date && dateRange.order_date.length === 2) || 
                      (dateRange.activation_date && dateRange.activation_date.length === 2);
                      
  return hasQueryParams || hasDateRange;
});

// 初始化
onMounted(() => {
  getList();
  loadProductOptions();
  loadUserOptions();
  loadInitialCustomerOptions();
});

// 监听激活日期变化，自动设置下单日期
watch(() => orderForm.activation_date, (newValue) => {
  // 只在添加新订单时才自动设置下单日期
  if (newValue && !orderForm.id && dialogTitle.value === '添加订单记录') {
    // 自动设置下单日期与激活日期相同
    orderForm.order_date = newValue;
    // 自动设置订单状态为已激活(1)
    orderForm.order_status = 1;
    console.log('已自动设置下单日期与激活日期同步:', newValue);
    console.log('已自动设置订单状态为已激活');
  }
});

// 获取订单列表
const getList = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    const params = { ...queryParams };
    if (dateRange.order_date && dateRange.order_date.length === 2) {
      params.order_date_start = dateRange.order_date[0];
      params.order_date_end = dateRange.order_date[1];
    }
    if (dateRange.activation_date && dateRange.activation_date.length === 2) {
      params.activation_date_start = dateRange.activation_date[0];
      params.activation_date_end = dateRange.activation_date[1];
    }
    
    const response = await getOrderList(params);
    orderList.value = response.results || [];
    pagination.total = response.count || 0;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 获取产品选项
const loadProductOptions = async () => {
  try {
    const response = await getProductList({ page_size: 50 });
    productOptions.value = response.results || [];
    console.log('已加载产品选项:', productOptions.value.length);
  } catch (error) {
    console.error('加载产品选项失败:', error);
  }
};

// 获取用户选项
const loadUserOptions = async () => {
  try {
    // 获取所有用户，包括管理员和普通客服
    const response = await getUserList({ page_size: 30 });
    console.log('用户选项API响应:', response);
    
    let userData = [];
    
    // 处理不同的响应格式
    if (response && response.results && response.results.length > 0) {
      userData = response.results;
    } else if (response && response.data && response.data.items) {
      userData = response.data.items;
    } else if (response && response.data && response.data.length > 0) {
      userData = response.data;
    } else {
      // 如果无法获取数据，保留默认数据
      console.warn('无法从API获取用户选项，使用默认数据');
      userOptions.value = [
        { id: 1, nickname: '默认客服1', role: 0 },
        { id: 2, nickname: '默认客服2', role: 0 },
        { id: 3, nickname: '默认客服3', role: 0 },
        { id: 4, nickname: '管理员1', role: 1 }
      ];
      return;
    }
    
    // 格式化用户数据，添加角色信息
    if (userData && userData.length > 0) {
      const formattedData = userData.map(item => ({
        id: item.id,
        nickname: item.role === 1 ? `${item.nickname || `用户${item.id}`}` : (item.nickname || `用户${item.id}`),
        role: item.role || 0
      }));
      userOptions.value = formattedData;
      console.log('已加载用户选项:', userOptions.value.length);
    }
  } catch (error) {
    console.error('加载用户选项失败:', error);
    // 使用默认数据，包含管理员示例
    userOptions.value = [
      { id: 1, nickname: '默认客服1', role: 0 },
      { id: 2, nickname: '默认客服2', role: 0 },
      { id: 3, nickname: '默认客服3', role: 0 },
      { id: 4, nickname: '管理员1(不参与薪资)', role: 1 }
    ];
    console.warn('加载用户选项出错，使用默认数据');
  }
};

// 加载初始客户选项
const loadInitialCustomerOptions = async () => {
  try {
    const response = await getCustomerList({ page_size: 50 });
    customerOptions.value = response.results || [];
  } catch (error) {
    console.error('加载客户列表失败:', error);
  }
};

// 处理查询
const handleQuery = () => {
  pagination.page = 1;
  console.log('提交查询参数:', queryParams);
  getList();
};

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    if (key !== 'page' && key !== 'page_size') {
      queryParams[key] = null;
    }
  });
  dateRange.order_date = [];
  dateRange.activation_date = [];
  console.log('重置后的查询参数:', queryParams);
  handleQuery();
};

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加订单记录';
  resetOrderForm();
  orderForm.order_status = 0;
  
  // 确认用户选项是否已加载
  console.log('打开添加对话框时的用户选项:', userOptions.value);
  if (userOptions.value.length === 0) {
    // 如果用户选项为空，重新加载
    loadUserOptions().then(() => {
      console.log('重新加载后的用户选项:', userOptions.value);
    });
  }
  
  dialogVisible.value = true;
};

// 重置订单表单
const resetOrderForm = () => {
  // 清除所有字段，确保没有旧数据
  Object.keys(orderForm).forEach(key => {
    // 根据字段类型设置默认值
    switch(key) {
      case 'id':
        orderForm[key] = undefined; // 重要：清除ID，避免误更新
        break;
      case 'order_date':
        orderForm[key] = new Date().toISOString().slice(0, 10); // 今天日期
        break;
      case 'purchase_years':
        orderForm[key] = 1; // 默认购买1年
        break;
      case 'order_status':
      case 'is_invoice':
      case 'is_double_coms':
      case 'order_source':
        orderForm[key] = 0; // 默认为0
        break;
      case 'order_amount':
        orderForm[key] = 0; // 默认金额0
        break;
      default:
        orderForm[key] = null; // 其他字段默认为null
    }
  });
  
  // 如果有表单引用，也重置验证状态
  if (orderFormRef.value) {
    orderFormRef.value.resetFields();
  }
};

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑订单记录';
  try {
    const response = await getOrder(row.id);
    
    // 确保客户选项中包含当前订单的客户
    if (response.customer_name) {
      const existingCustomer = customerOptions.value.find(c => c.id === response.customer_name);
      if (!existingCustomer) {
        // 如果客户选项中没有当前客户，添加到选项中
        customerOptions.value.push({
          id: response.customer_name,
          customer_name: response.customer_name_display
        });
      }
    }
    
    // 先重置表单，确保没有残留数据
    resetOrderForm();
    
    // 设置ID字段，确保更新而不是创建新记录
    orderForm.id = response.id;
    
    // 然后填充其他字段
    Object.keys(orderForm).forEach(key => {
      if (response[key] !== undefined) {
        orderForm[key] = response[key];
      }
    });
    
    console.log('编辑订单，设置ID为:', orderForm.id);
    
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
  }
};

// 处理复制
const handleCopy = (row) => {
  dialogTitle.value = '添加订单记录';
  
  // 先重置表单
  resetOrderForm();
  
  // 确保客户选项中包含当前订单的客户
  if (row.customer_name) {
    const existingCustomer = customerOptions.value.find(c => c.id === row.customer_name);
    if (!existingCustomer) {
      // 如果客户选项中没有当前客户，添加到选项中
      customerOptions.value.push({
        id: row.customer_name,
        customer_name: row.customer_name_display
      });
    }
  }
  
  // 复制除id外的所有字段值
  Object.keys(row).forEach(key => {
    if (key !== 'id' && Object.prototype.hasOwnProperty.call(orderForm, key)) {
      orderForm[key] = row[key];
    }
  });
  
  // 重置一些特定字段
  orderForm.id = undefined; // 确保不会更新原记录
  orderForm.order_number = '';
  orderForm.activation_date = '';
  orderForm.order_status = 0;
  
  console.log('复制后的订单表单:', orderForm);
  
  dialogVisible.value = true;
};

// 处理查看
const handleView = async (row) => {
  try {
    const response = await getOrder(row.id);
    orderDetail.value = response;
    orderDetailVisible.value = true;
  } catch (error) {
    console.error(error);
  }
};

// 处理提交表单
const submitOrderForm = async () => {
  if (!orderFormRef.value) return;
  
  await orderFormRef.value.validate(async (valid) => {
    if (valid) {
      const formData = { ...orderForm };
      
      // 处理可为空的字段
      // 授权码是必填字段，如果为空，设置为默认值而不是null
      if (formData.authorization_code === '' || formData.authorization_code === null) {
        formData.authorization_code = '无';
      }
      
      // 授权域名如果为空，设置默认值
      if (formData.authorized_domain === '' || formData.authorized_domain === null) {
        formData.authorized_domain = '无';
      }
      
      // 如果订单备注为空字符串，则设为null
      if (formData.order_remarks === '') {
        formData.order_remarks = null;
      }
      
      // 如果激活日期为空字符串，则设为null
      if (formData.activation_date === '') {
        formData.activation_date = null;
      }
      
      // 如果昵称为空，则设为null
      if (formData.nickname === '') {
        formData.nickname = null;
      }
      
      try {
        console.log('正在提交订单数据:', formData);
        if (formData.id) {
          await updateOrder(formData.id, formData);
          ElMessage.success('更新成功');
        } else {
          await createOrder(formData);
          ElMessage.success('添加成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error('提交订单失败:', error);
        if (error.response && error.response.data) {
          console.error('错误详情:', error.response.data);
          // 显示后端返回的具体错误信息
          if (typeof error.response.data === 'object') {
            // 如果是对象，尝试格式化显示
            const errorMessages = [];
            Object.keys(error.response.data).forEach(key => {
              const value = error.response.data[key];
              if (Array.isArray(value)) {
                errorMessages.push(`${key}: ${value.join(', ')}`);
              } else {
                errorMessages.push(`${key}: ${value}`);
              }
            });
            ElMessage.error(errorMessages.join('\n'));
          } else {
            ElMessage.error(error.response.data || '提交失败，请检查表单数据');
          }
        } else {
          ElMessage.error('提交失败，请检查网络连接');
        }
      }
    }
  });
};

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  ElMessageBox.confirm('确认要删除选中的数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteOrders(selectedIds.value);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error(error);
    }
  }).catch(() => {});
};

// 处理批量标记开票
const handleBatchMarkInvoice = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要标记的数据');
    return;
  }
  
  ElMessageBox.confirm('确认要将选中的订单标记为已开票吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchMarkInvoice(selectedIds.value);
      ElMessage.success('标记成功');
      getList();
    } catch (error) {
      console.error(error);
    }
  }).catch(() => {});
};

// 处理导出
const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    // 准备导出参数
    const exportParams = { ...queryParams };
    
    // 处理日期范围
    if (dateRange.order_date && dateRange.order_date.length === 2) {
      exportParams.order_date_start = dateRange.order_date[0];
      exportParams.order_date_end = dateRange.order_date[1];
    }
    if (dateRange.activation_date && dateRange.activation_date.length === 2) {
      exportParams.activation_date_start = dateRange.activation_date[0];
      exportParams.activation_date_end = dateRange.activation_date[1];
    }
    
    console.log('开始导出，使用参数:', exportParams);
    ElMessage.info(isFiltered.value ? '正在导出筛选数据...' : '正在导出全部数据...');
    
    const response = await exportOrders(exportParams);
    
    // 获取文件名 - 根据是否有筛选设置不同的文件名
    const filename = isFiltered.value ? '订单筛选数据.xlsx' : '订单全部数据.xlsx';
    
    // 创建Blob链接并下载
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();
    URL.revokeObjectURL(link.href);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + (error.message || '未知错误'));
  } finally {
    exportLoading.value = false;
  }
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  queryParams.page_size = val;
  getList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.page = val;
  queryParams.page = val;
  getList();
};

// 处理表单中客户选择变化
const handleCustomerSelectChange = (value) => {
  if (value === 'create_new') {
    // 选择了创建新客户选项
    orderForm.customer_name = null; // 重置customer值
    // 打开新建客户对话框，并预填客户名称
    customerForm.customer_name = searchCustomerKeyword.value;
    customerDialogVisible.value = true;
  }
};

// 提交客户表单
const submitCustomerForm = async () => {
  if (!customerFormRef.value) return;
  
  await customerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('正在提交客户表单数据:', customerForm);
        const response = await createCustomer(customerForm);
        console.log('客户创建成功，服务器响应:', response);
        ElMessage.success('客户创建成功');
        
        // 将新创建的客户添加到客户选项中
        const newCustomer = {
          id: response.id,
          customer_name: response.customer_name
        };
        customerOptions.value.push(newCustomer);
        
        // 选中新创建的客户
        orderForm.customer_name = newCustomer.id;
        
        customerDialogVisible.value = false;
      } catch (error) {
        console.error('创建客户失败:', error);
        console.error('错误详情:', error.response ? error.response.data : '无响应数据');
        ElMessage.error(error.response?.data?.message || '创建客户失败，请检查网络或服务器状态');
      }
    }
  });
};

// 打开导入对话框
const handleImportClick = () => {
  importDialogVisible.value = true;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  importFile.value = null;
};

// 处理文件上传
const handleFileUpload = (options) => {
  console.log('文件上传处理函数被调用', options);
  
  // 获取文件对象
  const file = options.file;
  if (!file) {
    ElMessage.error('请选择文件');
    return;
  }
  
  // 文件类型检查
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!');
    return;
  }
  
  // 文件大小检查（限制10MB）
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return;
  }
  
  // 保存文件引用
  importFile.value = file;
  console.log('文件已保存到importFile变量', importFile.value);
  ElMessage.success('文件已选择: ' + file.name);
  
  // 告诉el-upload组件上传成功
  options.onSuccess();
};

// 下载导入模板
const downloadTemplate = () => {
  importLoading.value = true;
  getImportTemplate()
    .then(response => {
      const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '订单导入模板.xlsx';
      link.click();
      URL.revokeObjectURL(link.href);
      ElMessage.success('模板下载成功');
      importLoading.value = false;
    })
    .catch(error => {
      console.error('下载模板失败:', error);
      ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      importLoading.value = false;
    });
};

// 提交导入文件
const submitImport = () => {
  console.log('提交导入，检查文件:', importFile.value);
  
  // 检查是否有上传文件
  const hasUploadFiles = uploadRef.value && uploadRef.value.uploadFiles && uploadRef.value.uploadFiles.length > 0;
  console.log('是否有上传文件:', hasUploadFiles);
  
  // 如果没有找到文件，显示错误提示
  if (!hasUploadFiles && !importFile.value) {
    ElMessage.error('请先选择文件');
    return;
  }
  
  // 准备要上传的文件
  let fileToUpload = null;
  
  // 优先使用upload组件中的文件
  if (hasUploadFiles) {
    fileToUpload = uploadRef.value.uploadFiles[0].raw;
    console.log('使用上传组件中的文件:', fileToUpload ? fileToUpload.name : 'undefined');
  }
  
  // 如果upload组件中没有文件，则使用直接保存的文件引用
  if (!fileToUpload && importFile.value) {
    fileToUpload = importFile.value;
    console.log('使用备用文件引用:', fileToUpload.name);
  }
  
  // 最终确认是否有文件可上传
  if (!fileToUpload) {
    ElMessage.error('无法获取文件对象，请重新选择文件');
    return;
  }
  
  // 检查文件类型
  const isExcel = 
    fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
    fileToUpload.type === 'application/vnd.ms-excel' ||
    fileToUpload.name.endsWith('.xlsx') ||
    fileToUpload.name.endsWith('.xls');
    
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件(.xlsx或.xls)');
    return;
  }
  
  importLoading.value = true;
  console.log('开始导入文件:', fileToUpload.name);
  
  // 优先使用api中定义的importOrders函数
  importOrders(fileToUpload)
    .then(response => {
      console.log('导入响应:', response);
      let responseData = response;
      
      // 尝试处理不同的响应格式
      if (response && response.data) {
        responseData = response.data;
      }
      
      if (responseData.success || responseData.code === 200) {
        ElMessage.success(responseData.message || '导入成功');
        
        // 如果有错误信息，也显示出来
        if (responseData.errors && responseData.errors.length > 0) {
          const errorMsg = responseData.errors.join('\n');
          // 使用对话框显示详细错误
          ElMessageBox.alert(errorMsg, '部分数据导入失败', {
            confirmButtonText: '确定',
            type: 'warning'
          });
        }
        
        // 导入成功后刷新订单列表
        getList();
        // 重置导入状态
        importFile.value = null;
        importDialogVisible.value = false;
      } else {
        // 显示错误信息
        if (responseData.errors && responseData.errors.length > 0) {
          const errorMsg = responseData.errors.join('\n');
          ElMessageBox.alert(errorMsg, '导入失败', {
            confirmButtonText: '确定',
            type: 'error'
          });
        } else {
          ElMessage.error(responseData.message || '导入失败');
        }
        console.error('导入返回错误:', responseData);
      }
    })
    .catch(error => {
      console.error('导入异常:', error);
      let errorMsg = '导入失败，请检查文件格式或网络连接';
      
      // 尝试提取详细错误信息
      if (error.response && error.response.data) {
        if (typeof error.response.data === 'string') {
          errorMsg = error.response.data;
        } else if (error.response.data.message) {
          errorMsg = error.response.data.message;
        } else if (error.response.data.detail) {
          errorMsg = error.response.data.detail;
        }
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      ElMessage.error(errorMsg);
    })
    .finally(() => {
      importLoading.value = false;
    });
};

</script>

<style scoped>
.customer-select-wrapper {
  position: relative;
}

.create-customer-btn {
  position: absolute;
  right: 0;
  top: -30px;
  font-size: 14px;
}

.import-dialog {
  height: 550px;
}

.import-container {
  padding: 16px;
  height: 100%;
}

.template-download {
  margin-bottom: 20px;
}

.upload-section {
  margin-top: 20px;
}

.import-format-container {
  height: 100%;
  padding-left: 10px;
}

.import-format-tips {
  background-color: #f5f7fa;
  border-left: 4px solid #0071e3;
  padding: 12px 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  max-height: 420px;
  overflow-y: auto;
}

.import-format-tips p {
  margin: 8px 0;
}

.import-format-tips ul {
  margin: 8px 0;
  padding-left: 20px;
}

.import-format-tips li {
  margin: 6px 0;
  line-height: 1.5;
}

.upload-box {
  width: 100%;
  margin-top: 16px;
}

/* 苹果风格卡片 */
.apple-card {
  border-radius: 12px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 4px 8px rgba(0, 0, 0, 0.03) !important;
  transition: box-shadow 0.3s ease, transform 0.2s ease;
  margin-bottom: 20px;
  border: none !important;
  overflow: hidden;
}

.apple-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 8px 16px rgba(0, 0, 0, 0.06) !important;
}

/* 苹果风格按钮 */
.apple-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: background-color 0.3s, transform 0.1s, box-shadow 0.3s !important;
  border: none !important;
  padding: 10px 16px !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08) !important;
}

.apple-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12) !important;
}

.apple-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

.primary-button {
  background-color: #0071e3 !important;
  color: white !important;
}

.primary-button:hover {
  background-color: #0077ed !important;
}

.danger-button {
  background-color: #ff3b30 !important;
  color: white !important;
}

.danger-button:hover {
  background-color: #ff453a !important;
}

.warning-button {
  background-color: #ff9500 !important;
  color: white !important;
}

.warning-button:hover {
  background-color: #ffa01e !important;
}

.success-button {
  background-color: #34c759 !important;
  color: white !important;
}

.success-button:hover {
  background-color: #30d158 !important;
}

/* 苹果风格表格 */
.apple-table {
  border-radius: 8px !important;
  overflow: hidden;
  border: none !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
}

.apple-table .el-table__header-wrapper {
  background-color: #f5f7fa !important;
}

.apple-table th.el-table__cell {
  background-color: #f5f7fa !important;
  font-weight: 600 !important;
  color: #333 !important;
  padding: 12px 0 !important;
}

.apple-table .el-table__row:hover td {
  background-color: #f5f9fc !important;
}

/* 链接按钮样式 */
.apple-link-button {
  font-weight: 500 !important;
  transition: color 0.3s !important;
}

.apple-link-button:hover {
  text-decoration: underline !important;
}

/* 苹果标签样式 */
.apple-tag {
  border-radius: 12px !important;
  padding: 2px 10px !important;
  font-weight: 500 !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08) !important;
}

/* 苹果风格表单元素 */
.apple-input .el-input__wrapper,
.apple-select .el-input__wrapper,
.apple-date-picker .el-input__wrapper {
  border-radius: 8px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
}

.apple-input .el-input__wrapper:hover,
.apple-select .el-input__wrapper:hover,
.apple-date-picker .el-input__wrapper:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-input .el-input__wrapper.is-focus,
.apple-select .el-input__wrapper.is-focus,
.apple-date-picker .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 苹果风格单选框组 */
.apple-radio-group .el-radio__label {
  font-size: 14px !important;
}

.apple-radio-group .el-radio__inner {
  border-color: #d9d9d9 !important;
  transition: all 0.3s !important;
}

.apple-radio-group .el-radio__input.is-checked .el-radio__inner {
  background-color: #0071e3 !important;
  border-color: #0071e3 !important;
}

.apple-radio-group .el-radio__input.is-checked+.el-radio__label {
  color: #0071e3 !important;
}

/* 分页控件样式 */
.apple-pagination {
  margin-top: 16px;
  padding: 8px 0;
}

.apple-pagination .el-pagination__sizes .el-input .el-input__wrapper {
  border-radius: 8px !important;
}

.apple-pagination .el-pager li {
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
  margin: 0 3px !important;
}

.apple-pagination .el-pager li.is-active {
  background-color: #0071e3 !important;
  color: white !important;
  font-weight: 600 !important;
}

.apple-pagination .btn-prev,
.apple-pagination .btn-next {
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
}

/* 调整表格排序图标位置 */
.el-table th.el-table__cell {
  text-align: left;
}

.el-table th.el-table__cell > .cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 排序图标显示在文本右边 */
.el-table .sort-caret-wrapper {
  position: static !important;
  display: inline-flex;
  align-items: center;
  margin-left: 5px;
}

.el-table .cell {
    box-sizing: border-box;
    line-height: 23px;
    overflow: hidden;
    overflow-wrap: break-word;
    padding: 0 12px;
    text-overflow: ellipsis;
    white-space: normal;
    display: flex; /* 添加这行 */
    flex-direction: row; /* 添加这行 */
    align-items: center; /* 可选：垂直居中对齐 */
    justify-content: flex-start; /* 可选：左对齐 */
}

/* 排序箭头垂直排列 */
.el-table .sort-caret.ascending,
.el-table .sort-caret.descending {
  position: static !important;
  margin: 2px 0;
}

/* 调整排序箭头高亮颜色 */
.el-table .ascending .sort-caret.ascending {
  border-bottom-color: #0071e3 !important;
}

.el-table .descending .sort-caret.descending {
  border-top-color: #0071e3 !important;
}

/* 表格行交替颜色 */
.apple-table .el-table__row:nth-child(odd) {
  background-color: #fafbfc;
}

/* 表格布局 */
.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.left-buttons, .right-buttons {
  display: flex;
  gap: 10px;
}

/* 订单详情样式 */
.order-detail-container {
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", sans-serif;
}

.info-text {
  font-size: 14px;
  color: #303133;
}

.price-text {
  font-size: 15px;
  color: #f56c6c;
  font-weight: bold;
}

.status-tag {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  line-height: 1.5;
  font-weight: 500;
}

.activated {
  background-color: #34c759;
  color: white;
}

.unactivated {
  background-color: #ff9500;
  color: white;
}

.yes {
  background-color: #0071e3;
  color: white;
}

.no {
  background-color: #8e8e93;
  color: white;
}
</style>

<!-- 添加全局样式 -->
<style>
/* 苹果风格对话框 */
.apple-dialog {
  border-radius: 12px !important;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15), 0 5px 15px rgba(0, 0, 0, 0.08) !important;
}

.apple-dialog .el-dialog__header {
  padding: 16px 20px !important;
  margin: 0 !important;
  border-bottom: 1px solid #f0f0f0 !important;
  background-color: #f5f7fa !important;
}

.apple-dialog .el-dialog__title {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #333 !important;
}

.apple-dialog .el-dialog__body {
  padding: 20px !important;
}

.apple-dialog .el-dialog__footer {
  padding: 12px 20px 16px !important;
  border-top: 1px solid #f0f0f0 !important;
}

.apple-dialog .el-dialog__headerbtn {
  top: 16px !important;
  right: 16px !important;
}

.apple-dialog .el-dialog__headerbtn:hover .el-dialog__close {
  color: #0071e3 !important;
}

/* 文件上传区域样式 */
.el-upload-dragger {
  border-radius: 12px !important;
  transition: all 0.3s ease !important;
  border: 2px dashed #dcdfe6 !important;
}

.el-upload-dragger:hover {
  border-color: #0071e3 !important;
  background-color: rgba(0, 113, 227, 0.05) !important;
}

/* 描述列表样式 */
.el-descriptions {
  border-radius: 8px !important;
  overflow: hidden !important;
}

.el-descriptions__header {
  margin-bottom: 15px !important;
}

.el-descriptions__title {
  font-weight: 600 !important;
  color: #333 !important;
}

.el-descriptions__label {
  font-weight: 600 !important;
  color: #606266 !important;
}

.el-descriptions__content {
  padding: 10px 15px !important;
}

/* 表单元素样式 */
.el-form-item__label {
  font-weight: 500 !important;
  color: #333 !important;
}

.el-input-number.is-controls-right .el-input-number__decrease, 
.el-input-number.is-controls-right .el-input-number__increase {
  border-radius: 0 8px 8px 0 !important;
}

/* 弹窗内部表格样式 */
.el-table--border {
  border-radius: 8px;
  overflow: hidden;
}

/* 信息提示框样式 */
.el-message {
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  padding: 12px 16px !important;
}

.el-message__content {
  font-size: 14px !important;
}

/* 加载状态样式 */
.el-loading-mask {
  backdrop-filter: blur(4px) !important;
  background-color: rgba(255, 255, 255, 0.6) !important;
}

/* 表单控件 */
.el-textarea__inner {
  border-radius: 8px !important;
  padding: 8px 12px !important;
  transition: box-shadow 0.3s ease !important;
}

.el-textarea__inner:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.el-textarea__inner:focus {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}
</style>

<style>
/* 查找.app-container样式并修改 */
.app-container {
  padding: 20px;
  height: calc(100vh - 84px); /* 增加容器高度，使用视口高度减去导航栏和页头高度 */
  overflow-y: auto; /* 添加垂直滚动 */
}
</style> 